package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.TimeUtil;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.enums.FlowStatusEnum;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdQualityRevSu;
import com.ccp.dev.qbdms.model.WQbdQualitymanageSu;
import com.ccp.dev.qbdms.model.WQbdXhdh;
import com.ccp.dev.qbdms.service.WQbdQualityRevSuService;
import com.ccp.dev.qbdms.service.WQbdXhdhService;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;

import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysRole;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.DictionaryService;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.qbdms.model.WQbdQualityReview;
import com.ccp.dev.qbdms.service.WQbdQualityReviewService;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;

import com.ccp.dev.workflow.model.ProcessRun;
import com.ccp.dev.workflow.model.TaskOpinion;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
import com.ccp.dev.workflow.service.TaskOpinionService;
import com.google.common.collect.Maps;
import java.util.*;

import com.ccp.dev.system.util.SysRoleUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.util.BaseUtil;

/**
 * 质量评审管理 信息操作处理控制器
 * 
 * @author prh
 * @date 2020-10-15 10:32:25
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "质量评审管理")
@RequestMapping("/qbdms/wQbdQualityReview")
public class WQbdQualityReviewController extends SysBaseController{
    @Resource
    private WQbdQualityReviewService wQbdQualityReviewService;
    @Resource
    private WQbdQualityRevSuService wQbdQualityRevSuService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;
    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private WQbdXhdhService wQbdXhdhService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private ProcessRunService processRunService;
    @Resource
    private TaskOpinionService taskOpinionService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: prh
     * @date: 2020-10-15 10:32:25
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到质量评审管理首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        wCustomColumnsService.addCustomCols(request);
        // 当前系统等级
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        modelMap.put("currentSystemLevel", currentSystemLevel);
        // 当前登录用户id
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        SysRole sysRole = (SysRole) request.getSession().getAttribute(SysRole.CURRENT_SYSROLE);
        modelMap.put("rolealis", sysRole.getAlias());

        //评审级别
        setDicToModelMap("psjb", modelMap);
        //评审结论
        setDicToModelMap("psjl", modelMap);
        //评审类别
        setDicToModelMap("pslb", modelMap);
        //是否存在问题
        setDicToModelMap("sfczwt", modelMap);
        //专业
        setDicToModelMap("zy", modelMap);

        // 型号代号
        List<WQbdXhdh> wQbdXhdhs = wQbdXhdhService.getAll();
        modelMap.put("wQbdXhdhs", JSON.toJSONString(wQbdXhdhs));

        return "wQbdQualityReview/list";
    }

    private void setDicToModelMap(String key, ModelMap modelMap) {
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey(key, false);
        modelMap.put(key + "List", JSON.toJSONString(dicList));
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: prh
    * @date: 2020-10-15 10:32:25
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询质量评审管理",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            // 没有排序,默认按照课题评审会会议时间倒序排列,课题评审会会议时间相同的情况下按创建时间倒序排列
            queryFilter.addFilter("orderField", "reviewdate");
            queryFilter.addFilter("orderSeq", "desc");
        }
        // 添加通用查询条件
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WQbdQualityReview> pageDatas = wQbdQualityReviewService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEditByFlowStatus(pageDatas);

        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: prh
     * @date: 2020-10-15 10:32:25
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到质量评审管理新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);

        String flag = RequestUtil.getString(request, "flag");
        modelMap.put("flag", flag);
        String runId="";
        List<TaskOpinion> taskOpinionNewList = new ArrayList<TaskOpinion>();
        ProcessRun processRun=processRunService.getByBusinessKey(id);
        if(BeanUtils.isNotEmpty(processRun)){
            runId=processRun.getRunId();
            List<TaskOpinion> taskOpinionList = taskOpinionService.getByRunId(runId);
            for(TaskOpinion taskOpinion:taskOpinionList){
                if(taskOpinion.getEndTime()!=null){
                    taskOpinionNewList.add(taskOpinion);
                }
            }
        }
        modelMap.put("taskOpinionNewList", taskOpinionNewList);
        if (StringUtils.isNotBlank(id)) {
            WQbdQualityReview wQbdQualityReview = wQbdQualityReviewService.getOneById(id);
            modelMap.put("flowStatus", wQbdQualityReview.getFlowStatus());
        }

        List<SysOrg> listOrg = new ArrayList<SysOrg>();
        listOrg = sysOrgService.queryAll();
        modelMap.put("researchRoomList", JSON.toJSONString(listOrg));

        if (StringUtil.isEmpty(id)) {
            SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
            SysOrg sysOrg = (SysOrg) ContextUtil.getCurrentOrg();
            modelMap.put("filldept", sysOrg.getOrgName());
            modelMap.put("fillman", sysUser.getFullName());
            modelMap.put("filldate", TimeUtil.getCurrentDate());
            modelMap.put("fillmanaccount", sysUser.getAccount());
            modelMap.put("filldeptid", sysOrg.getCode());
            modelMap.put("fillmanid", sysUser.getUserId());
        } else {
            //TODO 责任人时为反馈
//            if () {
                modelMap.put("isInclude", "false");
//            }
        }

        // 型号代号
        List<WQbdXhdh> wQbdXhdhs = wQbdXhdhService.getAll();
        modelMap.put("wQbdXhdhs", JSON.toJSONString(wQbdXhdhs));

        //评审级别
        setDicToModelMap("psjb", modelMap);
        //评审结论
        setDicToModelMap("psjl", modelMap);
        //评审类别
        setDicToModelMap("pslb", modelMap);
        //是否存在问题
        setDicToModelMap("sfczwt", modelMap);
        //专业
        setDicToModelMap("zy", modelMap);
        SysRole currentRole = SysRoleUtil.getCurrentRole(request);
        if (currentRole.getAlias().equals("bpm_xhzly")){
            modelMap.put("bpm_xhzly",true);
        }else{
            modelMap.put("bpm_xhzly",false);
        }
        return "wQbdQualityReview/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdQualityReview 保存的对象
    * @return: java.lang.Object
    * @auther: prh
    * @date: 2020-10-15 10:32:25
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存质量评审管理数据",detail="<#if isAdd>新增<#else>编辑</#if>质量评审管理数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>成功></#if>")
    public Object save(@RequestBody WQbdQualityReview wQbdQualityReview,HttpServletRequest request) {
        String id = wQbdQualityReview.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机Id
            wQbdQualityReview.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdQualityReview);

            wQbdQualityReview.setTenantId(ContextUtil.getCurrentUserTenantId());
            wQbdQualityReview.setCreateBy(ContextUtil.getCurrentUserId());
            wQbdQualityReview.setCreateTime(new Date());
            wQbdQualityReview.setFlowStatus(FlowStatusEnum.NOT_SUBMIT.getValue());
            result = wQbdQualityReviewService.add(wQbdQualityReview);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdQualityReview);

            wQbdQualityReview.setUpdateBy(ContextUtil.getCurrentUserId());
            wQbdQualityReview.setUpdateTime(new Date());
            result = wQbdQualityReviewService.update(wQbdQualityReview,request);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdQualityReviewService.getOneById(id), wQbdQualityReview));
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        Map<String,Object> idMap= Maps.newHashMap();
        idMap.put("id",wQbdQualityReview.getId());
        return result > 0 ? getResultDataSuccess("save.success",idMap) : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: prh
    * @date: 2020-10-15 10:32:25
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到质量评审管理详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String flag = RequestUtil.getString(request, "flag");
        modelMap.put("flag", flag);
        SysRole currentRole = SysRoleUtil.getCurrentRole(request);
        if (currentRole.getAlias().equals("bpm_xhzly")){
            modelMap.put("bpm_xhzly",true);
        }else{
            modelMap.put("bpm_xhzly",false);
        }
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        String runId="";
        List<TaskOpinion> taskOpinionNewList = new ArrayList<TaskOpinion>();
        ProcessRun processRun=processRunService.getByBusinessKey(id);
        if(BeanUtils.isNotEmpty(processRun)){
            runId=processRun.getRunId();
            List<TaskOpinion> taskOpinionList = taskOpinionService.getByRunId(runId);
            for(TaskOpinion taskOpinion:taskOpinionList){
                if(taskOpinion.getEndTime()!=null){
                    taskOpinionNewList.add(taskOpinion);
                }
            }
        }
        modelMap.put("taskOpinionNewList", taskOpinionNewList);
        WQbdQualityReview wQbdQualityReview = wQbdQualityReviewService.getOneById(id);
        modelMap.put("flowStatus", wQbdQualityReview.getFlowStatus());
        modelMap.put("runId", runId);
        modelMap.put("processRun", processRun);
        return "wQbdQualityReview/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: prh
    * @date: 2020-10-15 10:32:25
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询质量评审管理的一条数据",detail="根据主键id查询质量评审管理的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id,HttpServletRequest request) {
        WQbdQualityReview wQbdQualityReview = wQbdQualityReviewService.getOneById(id);
        List<WQbdQualityRevSu> wQbdQualityRevSus = wQbdQualityRevSuService.getListByRefId(id);
        //根据责任人进行数据筛选
        SysRole currentRole = SysRoleUtil.getCurrentRole(request);
        String currentUserId = ContextUtil.getCurrentUserId();
        String flag = RequestUtil.getString(request, "flag");
       if (flag.equals("2")){
           ZhiLiangConst.showWQbdQualityRevSu(wQbdQualityRevSus,currentUserId);
       }
        wQbdQualityReview.setwQbdQualityRevSuList(wQbdQualityRevSus);
        if (null == wQbdQualityReview) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        FlowStatusEnum flowStatusEnum = FlowStatusEnum.getEnumByValue(wQbdQualityReview.getFlowStatus());
        wQbdQualityReview.setFlowStatusStr(flowStatusEnum.getName());
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdQualityReview);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: prh
    * @date: 2020-10-15 10:32:25
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除质量评审管理数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) throws Exception{
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdQualityReview wQbdQualityReview = wQbdQualityReviewService.getOneById(key);
            if (!userId.equals(wQbdQualityReview.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        //流程实例删除
        for (String key : ids) {
            WQbdQualityReview wQbdQualityReview = wQbdQualityReviewService.getOneById(key);
            if(!wQbdQualityReview.getFlowStatus().equals(FlowStatusEnum.NOT_SUBMIT.getValue()) && StringUtil.isNotEmpty(wQbdQualityReview.getFlowStatus())){
                ProcessRun processRun = processRunService.getByBusinessKey(key);
                if(!(wQbdQualityReview.getFlowStatus().equals(FlowStatusEnum.DONE.getValue()))){
                    if(processRun!=null){
                        processRunService.recoverByRunId(processRun.getRunId());
                    }
                }
                if(processRun!=null){
                    processRunService.deleteByProcessRun(processRun);
                }
            }
        }
        int result = wQbdQualityReviewService.delByIdArray(id.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
    * 功能描述: 跳转到导出选择字段页面
    *
    * @param: [request] http请求
    * @param: modelMap
    * @return: java.lang.String
    * @auther: prh
    * @date: 2020-10-15 10:32:25
    * @throws Exception
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到质量评审管理导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdQualityReview.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
    * 功能描述: 导出质量评审管理数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: prh
    * @date: 2020-10-15 10:32:25
    */
    @RequestMapping("/exportData")
    @Action(description="导出质量评审管理数据信息",detail="导出质量评审管理数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        List<WQbdQualityReview> list = this.wQbdQualityReviewService.queryAll(queryFilter);
        if (list.isEmpty()) {
            list.add(new WQbdQualityReview());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, list, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
     * 功能描述: 启动流程
     */
    @PostMapping("/run")
    @ResponseBody
    @Action(description="启动质量评审管理流程",detail="启动流程<#if success>成功<#else></#if>")
    public Object run(HttpServletRequest request,@RequestBody WQbdQualityReview wQbdQualityReview){
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        //实体主键
        String id = wQbdQualityReview.getId();
        int isList = RequestUtil.getInt(request,"isList",1);
        ProcessCmd  processCmd = new ProcessCmd();
        //流程Key
        processCmd.setModelKey("zlpssplc");
        processCmd.setUserAccount(sysUser.getAccount());
        try {
            if(isList == 1){
                wQbdQualityReview = wQbdQualityReviewService.getOneById(id);
            }
            processCmd.setBusinessKey(id);
            processRunService.startProcess(processCmd);
            wQbdQualityReview.setFlowStatus(FlowStatusEnum.APPROVAL_ING2.getValue());
            wQbdQualityReviewService.update(wQbdQualityReview);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("flow.start.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("flow.start.failure");
        }
    }
}
